//
//  AverageViewController.m
//  JinChengYun
//
//  Created by 金橙云 on 2017/3/9.
//  Copyright © 2017年 金橙云. All rights reserved.
//

#import "AverageViewController.h"
#import "UIView+Frame.h"
#import "ListChartView.h"
#import "FTPopOverMenu.h"
#import "ZFLineChart.h"//
#import "TodoHttpManager.h"

#define B_WIDTH (self.view.frame.size.width)
#define B_HEIGHT (self.view.frame.size.height)
#define EVERY_Wi (self.view.frame.size.width)/5

@interface AverageViewController ()<ListChartViewDelegate,ZFGenericChartDataSource,ZFLineChartDelegate>{
    UIButton *_selectTypeBtn;
    NSInteger segmentIdex;//记录按某种类型查看网格segment的index
    NSInteger segmentIdex2;//记录年月segment的index
    NSArray *_hengyiArr;
    NSInteger xialainteger;//记录点击下拉列表的第几个
}

@property(nonatomic,strong)UISegmentedControl *segmented;//记录按某种类型查看网格segment
@property(nonatomic,strong)UISegmentedControl *segmented2;//记录年月segment

@property(nonatomic,strong)UIScrollView *scrollerView;

@property(nonatomic,strong)ListChartView *chatView;

@property (nonatomic, strong) ZFLineChart * lineChart;

@property(nonatomic,strong)NSMutableDictionary *biaoDic;
@property(nonatomic,strong)NSMutableDictionary *tuDic;

@property (nonatomic, strong) NSArray         *zuoyishuArr;//左一 物业类型+期数
@property (nonatomic, strong) NSArray         *nozuiyiArr;//无左一 物业类型+期数
@property (nonatomic, strong) NSDictionary         *xialiDic;//下来字典 ID+name两个数组
@property (nonatomic, strong) NSArray         *zhexiantuArr;//折线图 年+月
@end

@implementation AverageViewController
-(void)viewWillAppear:(BOOL)animated
{
    //  均价动态表数据() 均价动态--物业类型获取
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDManagerFirstJunJia:) name:TDManagerFirstJunJia object:nil];
    
    [_manager userManagerFirstJunJiaDynamic];
    //均价动态图数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTDManagerFirstJunBiao:) name:TDManagerFirstJunBiao object:nil];
    
   // [_manager userManagerFirstJunJiaBiaoDynamicWithType:nil];
    
    _biaoDic = [NSMutableDictionary new];
    _tuDic = [NSMutableDictionary new];
    
    
    
    [_chatView reloadData];
    [_lineChart strokePath];
    
}
-(void)didTDManagerFirstJunJia:(NSNotification *)noti
{
    if (noti.object != 0)
    {
        _biaoDic = [noti.object objectForKey:@"data"];
        NSLog(@"---------bioaDic--%@",_biaoDic);////表 包括下拉列表
        /**表
         物业类型
         */
        NSLog(@"_biaoDic===%@",_biaoDic);
        NSMutableArray *welxzuoyiArr = [NSMutableArray new];
        NSMutableArray *welxnoZuoYiArr = [NSMutableArray new];
        NSMutableArray *welxArr = [_biaoDic objectForKey:@"wylx"];//物业类型查看表
        for (int i=0; i<welxArr.count; i++) {
            NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] initWithCapacity:0];
            tmpDic= welxArr[i];
            
            [welxzuoyiArr addObject:tmpDic[@"name"]];//按物业类型查看的纵坐标左一直
            NSArray *arr = [NSMutableArray arrayWithObjects:tmpDic[@"month_jun"],tmpDic[@"ht_jun"],tmpDic[@"unsale_jun"],tmpDic[@"zonghe_jun"], nil];
            [welxnoZuoYiArr addObject:arr];
            
            
        }
        NSLog(@"welxnoZuoYiArr==%@",welxnoZuoYiArr);
        /**表
         期数
         */
        NSMutableArray *qishuzuoyiArr = [[NSMutableArray alloc] init];
        NSMutableArray *qishunoZuoYiArr = [[NSMutableArray alloc] init];
        NSArray *qishuArr = [_biaoDic objectForKey:@"qishu"];//期数查看表
        for (int i=0; i<welxArr.count; i++) {
            NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] initWithCapacity:0];
            tmpDic= qishuArr[i];
            
            [qishuzuoyiArr addObject:tmpDic[@"name"]];//的纵坐标左一直
            NSArray *arr = [NSMutableArray arrayWithObjects:tmpDic[@"month_jun"],tmpDic[@"ht_jun"],tmpDic[@"unsale_jun"],tmpDic[@"zonghe_jun"], nil];
            [qishunoZuoYiArr addObject:arr];
            
        }
        
        
        _zuoyishuArr = [NSArray arrayWithObjects:welxzuoyiArr,qishuzuoyiArr, nil];
        NSLog(@"_zuoyishuArr==%@",_zuoyishuArr);
        _nozuiyiArr = [NSArray arrayWithObjects:welxnoZuoYiArr,qishunoZuoYiArr, nil];

        //下拉列表
        
        NSMutableArray *xialaArr = _biaoDic[@"wylx_name"];
        NSMutableArray *xialaiIDArr = [NSMutableArray new];
        NSMutableArray *xialaiNameArr = [NSMutableArray new];

        for (int i=0; i<xialaArr.count; i++) {
            [xialaiIDArr addObject: xialaArr[i][@"id"]];
            [ xialaiNameArr addObject: xialaArr[i][@"name"]];
            
        }
        _xialiDic = @{@"id":xialaiIDArr,@"name":xialaiNameArr};
        

        [_chatView reloadData];
    }
}

-(void)didTDManagerFirstJunBiao:(NSNotification *)notific
{
    if (notific.object != 0)
    {
        _tuDic = [notific.object objectForKey:@"data"];
        NSLog(@"22222---------_tuDic--%@",_tuDic);//折线图 xialiDic
        
        NSDictionary *yearDic =_tuDic[@"year"];;
        NSDictionary *monthDic =_tuDic[@"month"];;
        
        /**
         年
         */
        NSMutableArray *yearConArr = [NSMutableArray new];
        NSMutableArray *yearNameArr = [NSMutableArray new];
        NSMutableArray *yearCountArr = [NSMutableArray new];
        NSMutableArray *yearMaxDataArr = [NSMutableArray new];
        NSArray *yearAllArr = [NSArray new];

        NSMutableArray *yearMesArr = yearDic[@"message"];
        [yearCountArr addObject:monthDic[@"count"]];//点数目
        [yearMaxDataArr addObject:monthDic[@"max_data"]];//最大值
        for (int i=0; i<yearMesArr.count; i++) {
            NSDictionary *dic = yearMesArr[i];
            [yearConArr addObject:dic[@"con"]];//每个点的数字
            [yearNameArr addObject:dic[@"name"]];////每个点下表名称
            
        }
        yearAllArr = @[yearConArr,yearNameArr,yearCountArr,yearMaxDataArr];

        /**
         月
         */
        NSMutableArray *monthConArr = [NSMutableArray new];
        NSMutableArray *monthNameArr = [NSMutableArray new];
        NSMutableArray *monthCountArr = [NSMutableArray new];
        NSMutableArray *monthMaxDataArr = [NSMutableArray new];
        NSArray *monthAllArr = [NSArray new];

        NSMutableArray *monthMesArr = monthDic[@"message"];
        [monthCountArr addObject:monthDic[@"count"]];//点数目
        [monthMaxDataArr addObject:monthDic[@"max_data"]];//最大值
        for (int i=0; i<monthMesArr.count; i++) {
            NSDictionary *dic = monthMesArr[i];
            [monthConArr addObject:dic[@"con"]];//每个点的数字
            [monthNameArr addObject:dic[@"name"]];////每个点下表名称

        }
        
        monthAllArr= @[monthConArr,monthNameArr,monthCountArr,monthMaxDataArr];

        _zhexiantuArr = @[yearAllArr,monthAllArr];
        
        [_lineChart strokePath];
        
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDManagerFirstJunJia object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TDManagerFirstJunBiao object:nil];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    _manager = [TodoHttpManager sharedManager];
    
    _hengyiArr = @[@"类型",@"本月均价",@"已售均价",@"未售均价",@"综合均价"];
    
    _scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, B_HEIGHT)];
    _scrollerView.backgroundColor = [UIColor whiteColor];
    _scrollerView.contentSize = CGSizeMake(B_WIDTH, B_HEIGHT*1.2);
    [self.view addSubview:_scrollerView];
    
    //分段控件
    _segmented = [[UISegmentedControl alloc] initWithItems:@[@"按物业类型查看",@"按期数查看"]];
    _segmented.frame = CGRectMake(10, 0, B_WIDTH-10*2, 25);
    _segmented.selectedSegmentIndex = 0;//设置默认选择项索引
    _segmented.tag = 11;
    _segmented.tintColor = [UIColor orangeColor];
    [_segmented addTarget:self action:@selector(segmentedBtnClick:) forControlEvents:UIControlEventValueChanged];
    [_scrollerView addSubview:_segmented];

    //表格
    _chatView = [[ListChartView alloc] initWithFrame:CGRectMake(0, 35, B_WIDTH, 33*4)];
    [_chatView setBorderWidth:1.0f];
    [_chatView setDelegate:self];
    [_scrollerView addSubview:_chatView];
    [_chatView reloadData];
    

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_chatView.frame)+2,B_WIDTH , 25)];
    [view setBackgroundColor:[UIColor orangeColor]];
    [_scrollerView addSubview:view];
    
    UILabel *lb = [UILabel new];
    lb.frame = CGRectMake(10, 2, 150, 20);
    lb.textAlignment = NSTextAlignmentLeft;
    lb.text = @"主售房源均价动态";
    lb.textColor = [UIColor whiteColor];
    lb.font = [UIFont systemFontOfSize:14];
    [view addSubview:lb];
    
    //下拉弹框
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(B_WIDTH-130, 2, 120, 20);
    [btn setTitle:@"高层住宅" forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"Btn_seacher"] forState:UIControlStateNormal];
    
    [btn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
    
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.layer.borderWidth=1;
    btn.layer.borderColor = [UIColor whiteColor].CGColor;
    [btn setTag:1];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(xiaLaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    btn.layer.cornerRadius = 3;
    _selectTypeBtn =btn;
   
    //分段控件2 n年月
    _segmented2 = [[UISegmentedControl alloc] initWithItems:@[@"月",@"年"]];
    _segmented2.frame = CGRectMake(B_WIDTH-90, CGRectGetMaxY(view.frame)+5, 80, 30);
    _segmented2.selectedSegmentIndex = 0;//设置默认选择项索引
    _segmented2.tag = 12;
    _segmented2.tintColor = [UIColor orangeColor];
    [_segmented2 addTarget:self action:@selector(segmentedBtnClick:) forControlEvents:UIControlEventValueChanged];
    [_scrollerView addSubview:_segmented2];

    //折线图
    _lineChart = [[ZFLineChart alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segmented2.frame),SCREEN_WIDTH, 300)];
    self.lineChart.dataSource = self;
    self.lineChart.delegate = self;
    self.lineChart.isResetAxisLineMinValue = YES;
    self.lineChart.isShowXLineSeparate = YES;
    self.lineChart.isShowYLineSeparate = YES;
    self.lineChart.linePatternType = kLinePatternTypeForCurve;
    [_scrollerView addSubview:self.lineChart];
    [self.lineChart strokePath];
    
    segmentIdex  = 0;
    segmentIdex2 = 0;
    /**
     
     SDAutoLoyout 重新计算位置 自适应scrollView
     */
    

}

//
- (void)xiaLaBtnClick:(UIButton *)sender{
    
   // NSArray *arr = @[@"类型1",@"类型2",@"类型3",@"类型4"];
    [FTPopOverMenu showForSender:sender
                   withMenuArray:[_xialiDic objectForKey:@"name"]
                      imageArray:nil
                       doneBlock:^(NSInteger selectedIndex)//0 . . . .
     {
         [sender setTitle:[_xialiDic objectForKey:@"name"][selectedIndex] forState:UIControlStateNormal];
         /**
          筛选数据 给下面的折线图赋值
          */
       //获取到点击的是第几个item  无默认值 因为是每个item的ID
         NSString *sttt = [_xialiDic objectForKey:@"id"][selectedIndex];
         //_segmented2//代表的是年月 0 1  默认==年==0
        
         [_manager userManagerFirstJunJiaBiaoDynamicWithType:sttt];

         
     }
                    dismissBlock:^
     {
         
     }];

}
-(void)segmentedBtnClick:(UISegmentedControl *)sender
{
    if (sender.tag==11) {//查看类型的segment
        segmentIdex = sender.selectedSegmentIndex;
        
        [_chatView reloadData];
        
        //更新表格
    }
    if (sender.tag==12){//年月segment
        segmentIdex2 = sender.selectedSegmentIndex;
        
        
        [_lineChart strokePath];
        //更新折线图
    }
    
}


#pragma mark -- 网格
/**
 表格和折线图的 横纵的值均有服务器返回取值而得 不可写死
 */
////表单行数
-(NSInteger)rowForList:(ListChartView *)list
{
    NSArray *arr = _zuoyishuArr[segmentIdex];
    NSLog(@"count==%ld",arr.count);
   // return 4;
  
    return arr.count+1;
    /**
     需要更新控件的frame
     */
}
////表单列数
-(NSInteger)columnForList:(ListChartView *)list
{
    return 5;
}
/////表单某一格字体的颜色
-(UIColor*)listChart:(ListChartView *)list textColorForRow:(NSInteger)row column:(NSInteger)column
{
    
    if (row == 0 || column == 0)
    {
        return [UIColor orangeColor];
    }
    return nil;
}
/////表单某一格的大小
-(CGSize)listChart:(ListChartView *)list itemSizeForRow:(NSInteger)row column:(NSInteger)column
{
    return CGSizeMake(EVERY_Wi, 33.0f);
}
/////表单某一格的文字
-(NSString*)listChart:(ListChartView *)list textForRow:(NSInteger)row column:(NSInteger)column
{
    if (row == 0)
    {
        for (int i=0; i<_hengyiArr.count; i++) {
        IF_T_FF(row, column, 0, i){return _hengyiArr[i];}

        }
    }
    else if (column == 0)
    {
        NSLog(@"%ld",_zuoyishuArr.count);
        
        for (int i = 0; i<[_zuoyishuArr[segmentIdex] count]; i++) {
            IF_T_FF(row, column, i+1, 0)
            {return _zuoyishuArr[segmentIdex][i];}
            
        }

    }
/**
 这个地方处理的很不好 待处理
 */
    
    if (row==1) {
        for (int i=0; i<_hengyiArr.count-1; i++) {
            IF_T_FF(row, column, 1, i+1){return _nozuiyiArr[segmentIdex][0][i];}

            
        }

    }else if (row==2) {
        for (int i=0; i<_hengyiArr.count-1; i++) {
            IF_T_FF(row, column, 2, i+1){return _nozuiyiArr[segmentIdex][1][i];}
            
            
        }
        
    }else if (row==3) {
        for (int i=0; i<_hengyiArr.count-1; i++) {
            IF_T_FF(row, column, 3, i+1){return _nozuiyiArr[segmentIdex][2][i];}
            
            
        }
        
    }else{
        return 0;
    }
    
    return 0;
    
}
////点击触发事件
-(void)listChart:(ListChartView*)list clickForRow:(NSInteger)row column:(NSInteger)column{
    NSLog(@"点击网格row===%ld==column==%ld",(long)row,(long)column);
    
}

#pragma mark - ZFGenericChartDataSource 折线图
#pragma mark -  折线图 纵坐标
- (NSArray *)valueArrayInGenericChart:(ZFGenericChart *)chart{
    
    return (NSMutableArray *)_zhexiantuArr[segmentIdex2][0];
    
    
}
#pragma mark -  折线图 横坐标
/**
 *  组与组之间的间距(若不设置，默认为20.f)
 */
- (CGFloat)paddingForGroupsInLineChart:(ZFLineChart *)lineChart{
    return 60;
}

- (NSArray *)nameArrayInGenericChart:(ZFGenericChart *)chart{
   // NSLog(@"=1111111==%@",_zhexiantuArr[segmentIdex2][1]);
    return (NSMutableArray *)_zhexiantuArr[segmentIdex2][1];
    
}

- (NSArray *)colorArrayInGenericChart:(ZFGenericChart *)chart{
    //曲线的颜色
    return @[ZFLvColor];
    //return [];
}

- (CGFloat)axisLineMaxValueInGenericChart:(ZFGenericChart *)chart{
    return 100;
}

//背景格格
- (NSUInteger)axisLineSectionCountInGenericChart:(ZFGenericChart *)chart{
    //这里也可以根据服务器返回数据 重新布局
    return 1;
}


@end
